#!/bin/bash
#--------------------------------------------------
# @usage:    ./egg
# @system:   centos7
#--------------------------------------------------
set -o nounset
set -o errexit

### create supervisor conf ##################################################
function create_supervisord_conf()
{
  logger warn "new app name: ${APP_NAME}"
  logger warn "sleep time: ${SLEEP_TIME}"

  if [ ! -f $BASE/html/${APP_NAME}.html ];then
    echo -e "\033[31mhtml文件不存在\033[0m"
    exit 1;
  fi

  FIND_FILE="$BASE/html/PROJECT.md"
  if [ ! `grep -c "$APP_NAME" $FIND_FILE` -ne '0' ];then
    echo -e "\033[31m项目注释未完善\033[0m"
    exit 1;
  fi

  cp $BASE/supervisord.d/demo.bak $BASE/supervisord.d/${APP_NAME}.ini

  sed -i "s/APP_NAME/${APP_NAME}/g" $BASE/supervisord.d/${APP_NAME}.ini
  sed -i "s/SLEEP_TIME/${SLEEP_TIME}/g" $BASE/supervisord.d/${APP_NAME}.ini

  ((num = (600 / (5 + $SLEEP_TIME * 20)) * 20))

  echo -e "当前配置下预计每 10 分钟可以跑 ${num} 个\033[33m"
  cat $BASE/supervisord.d/${APP_NAME}.ini
  echo -e "\033[0m"
}

### reload supervisor ##################################################
function reload_supervisord()
{
  supervisorctl update
}

### show environment ##################################################
function show_set_environment()
{
    echo -e "\033[31mexport APP_NAME=\033[0m"
    echo -e "\033[31mexport SLEEP_TIME=\033[0m"
}

### Usage ##################################################
function usage() {
  echo -e "\033[33mUsage:\033[0m egg [options] [args]"
  cat <<EOF
  option: -{CRS}
    -C         create supervisor conf
    -R         reload supervisor
    -S         the command to set environment
EOF
}

### Main Lines ##################################################
function main() {
  BASE="/home/wwwroot/python-headless"

    # check if use bash shell
  readlink /proc/$$/exe|grep -q "dash" && { logger error "you should use bash shell, not sh"; exit 1; }
  # check if use with root
  [[ "$EUID" -ne 0 ]] && { logger error "you should run this script as root"; exit 1; }

  [[ "$#" -eq 0 ]] && { usage >&2; exit 1; }

  ACTION=""
  while getopts "CRS" OPTION; do
      case "$OPTION" in
        C)
          ACTION="create_supervisord_conf"
          ;;
        R)
          ACTION="reload_supervisord"
          ;;
        S)
          ACTION="show_set_environment"
          ;;
        ?)
          usage
          exit 1
          ;;
      esac
  done

  [[ "$ACTION" == "" ]] && { logger error "illegal option"; usage; exit 1; }

  # excute cmd "$ACTION"
  logger info "Action begin: $ACTION"
  ${ACTION} || { logger error "Action failed: $ACTION"; return 1; }
  logger info "Action successed: $ACTION"
}

main "$@"
